package cbnu.Imvision.BeWithYou;

import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

@SuppressLint("WorldReadableFiles")
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
	ImageView target;
	private static Context targetContext;

	public ImageDownloader(ImageView target, Context context) {
		this.target = target;
		ImageDownloader.targetContext = context;
	}

	@Override
	protected Bitmap doInBackground(String... urls) {
		return downloadBitmap(urls[0]);
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		target.setImageBitmap(result);
		super.onPostExecute(result);
	}

	static Bitmap downloadBitmap(String url) {
		String originalURL = url;
		
		final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
		if (url.matches("T.*")) {
			url = config.Config.TOUR_PIC_ADDRESS + url;
			Log.d("ImageDoundloader", "It's Tour Image file.\n" + url);
		} else if (url.matches("C.*")) {
			url = config.Config.CARE_PIC_ADDRESS + url;
			Log.d("ImageDoundloader", "It's Care Image file.\n" + url);
		}
		final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
					try {
						FileOutputStream fos;
						fos = targetContext.openFileOutput(originalURL, Context.MODE_WORLD_READABLE);
						bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return Bitmap.createScaledBitmap(bitmap, config.Config.SIZE_OF_ImageView,
							(int) (config.Config.SIZE_OF_ImageView * ((double) bitmap.getHeight() / (double) bitmap
									.getWidth())), false);
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (Exception e) {
			// Could provide a more explicit error message for IOException or
			// IllegalStateException
			getRequest.abort();
			Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + "\n" + e.toString());
		} finally {
			if (client != null) {
				client.close();
			}
		}
		return null;
	}
}
